<template>
	<div class="app-container">
		<!-- table start -->
		<el-table
			v-loading="listLoading"
			:data="orderGoodList"
			element-loading-text="Loading"
			border
			fit
			stripe
			show-summary
			highlight-current-row
			:row-style="{ height: '40px' }"
			:cell-style="{ padding: '5px 0' }"
			:row-class-name="tableRowClassName"
			@cell-dblclick="handleCellClick"
		>
			<el-table-column label="操作" width="200" type="index" align="center">
				<template slot-scope="scope">
					<el-button @click="showDialog(scope.$index)" size="mini">选择</el-button>
					<el-button @click="handleDelete(scope.$index)" size="mini">删除</el-button>
				</template>
			</el-table-column>
			<el-table-column label="商品名称" width="200" align="center">
				<template slot-scope="scope">
					{{ scope.row.goodName }}
				</template>
			</el-table-column>
			<el-table-column label="商品编号" width="" align="center">
				<template slot-scope="scope">
					{{ scope.row.goodNo }}
				</template>
			</el-table-column>
			<el-table-column label="可用库存" width="110" align="center">
				<template slot-scope="scope">
					<span>{{ scope.row.goodStock }}</span>
				</template>
			</el-table-column>
			<el-table-column label="销量" width="110" align="center">
				<template slot-scope="scope">
					<span>{{ scope.row.saleNum }}</span>
				</template>
			</el-table-column>
			<el-table-column label="售价(元)" width="110" align="center" >
				<template slot-scope="scope">
					<span>{{ scope.row.goodPrice }}</span>
				</template>
			</el-table-column>
			<el-table-column label="进货数量" min-width="150px" align="center">
				<template slot-scope="scope">
					<template v-if="scope.row.editQuantity">
						<el-input v-model="scope.row.quantity" 
						class="edit-input" 
						size="small" 
						@blur="handleInput(scope.row,'quantity')" 
						ref="cellInput1" autofocus="true"
						type="number"/>
					</template>
					<span v-else>{{ scope.row.quantity }}</span>
				</template>
			</el-table-column>
			<el-table-column min-width="150px" label="进货价" align="center">
				<template slot-scope="scope">
					<template v-if="scope.row.editPrice">
						<el-input v-model="scope.row.goodInPrice" 
						class="edit-input"
						size="small" 
						ref="cellInput2"
						type="number"
						@blur="handleInput(scope.row,'price')" />
					</template>
					<span v-else>{{ scope.row.goodInPrice }}</span>
				</template>
			</el-table-column>
			<el-table-column label="采购费用(元)" width="110" align="center" prop="totalPrice">
				<template slot-scope="scope">
					<span>{{ scope.row.totalPrice }}</span>
				</template>
			</el-table-column>
		</el-table>
		<!-- table end-->
		<!-- 选择商品 dialog start-->
		<el-dialog title="选择商品" :visible.sync="dialogVisible" width="80%">
			<div class="filter-container">
				<el-input v-model="listQuery.title" placeholder="商品货号或者名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
				<el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
				<el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="goGoodDetail">添加商品</el-button>
			</div>
			<el-table
				v-loading="listLoading"
				:data="goodList"
				element-loading-text="Loading"
				border
				fit
				max-height="300"
				stripe
				:row-style="{ height: '40px' }"
				:cell-style="{ padding: '5px 0' }"
				highlight-current-row
				@selection-change="handleSelectChange"
			>
				<el-table-column type="selection" width="55"></el-table-column>
				<el-table-column align="center" label="商品主图" width="95">
					<template slot-scope="scope">
						<el-image style="width: 30px; height: 30px" :src="scope.row.mainImage" :preview-src-list="[scope.row.mainImage]"></el-image>
					</template>
				</el-table-column>
				<el-table-column label="商品名称" width="">
					<template slot-scope="scope">
						{{ scope.row.goodName }}
					</template>
				</el-table-column>
				<el-table-column label="商品编号" width="200">
					<template slot-scope="scope">
						{{ scope.row.goodNo }}
					</template>
				</el-table-column>
				<el-table-column label="库存" width="110" align="center">
					<template slot-scope="scope">
						<span>{{ scope.row.goodStock }}</span>
					</template>
				</el-table-column>
				<el-table-column label="销量" width="110" align="center">
					<template slot-scope="scope">
						<span>{{ scope.row.saleNum }}</span>
					</template>
				</el-table-column>
				<el-table-column label="售价" width="110" align="center">
					<template slot-scope="scope">
						<span>{{ scope.row.goodPrice }}</span>
					</template>
				</el-table-column>
				<el-table-column label="平均成本价" width="110" align="center">
					<template slot-scope="scope">
						<span>{{ scope.row.cost }}</span>
					</template>
				</el-table-column>
			</el-table>
			<pagination v-show="total > 5" :total="total" :page.sync="pageNum" :limit.sync="pageSize" @sizeChange="handleSizeChange" @currentChange="handleCurrentChange" />
			<span slot="footer" class="dialog-footer"><el-button @click="storeColseDialog">保存并关闭</el-button></span>
		</el-dialog>
		<!-- 选择商品 dialog end-->
		<el-row type="flex" class="button-container" justify="center"><el-button type="primary" align="middle" @click="submit">提交进货单</el-button></el-row>
	</div>
</template>

<script>
import { getAll } from '@/api/good';
import { batch } from '@/api/purorder';
import Pagination from '@/components/Pagination'; // 分页组件

const orderGood = {
	goodName: '',
	goodNo: '',
	goodId:'',
	goodStock: '',
	goodInPrice: '',
	totalPrice: 0,
	quantity: 0,
	saleNum: '',
	editQuantity: false,
	editPrice: false,
	originalGoodInPrice: '' //用作编辑
};

export default {
	components: { Pagination },
	filters: {},
	data() {
		return {			
			orderGoodList: [
				{
					goodName: '',
					goodNo: '',
					goodId: '',
					goodStock: '',
					goodInPrice: 0,
					totalPrice: 0,
					quantity: 0,
					saleNum: '',
					editPrice: false,
					editQuantity:false
				}
			],
			goodList: [],
			listLoading: false,
			dialogVisible: false,
			listQuery: {
				title: ''
			},
			//页码
			pageNum: 1,
			//页数量
			pageSize: 10,
			//总数
			total: 10,
			tmpGoodList: [] //临时选择商品数组
		};
	},
	created() {},
	onShow() {
	},
	mounted() {
		console.log(this.$refs.cellInput1)
	},
	methods: {
		// 分页大小切换
		handleSizeChange(val) {
			this.pageNum = val;
			this.getAll();
		},
		// 页码切换
		handleCurrentChange(val) {
			this.pageNum = val;
			this.getAll();
		},
		//构造索引
		tableRowClassName ({row, rowIndex}) {
		      // 把每一行的索引放进row
		      row.index = rowIndex;
		},
		// 去添加商品
		goGoodDetail() {
			this.$router.push('/good/goodDetail');
		},
		// 搜索
		handleFilter() {},
		// 删除所选进货商品
		handleDelete(index) {
			if (this.orderGoodList.length == 1) {
				this.$message({
					message: '至少保留一条记录',
					type: 'warning'
				});
				return;
			}
			this.orderGoodList.splice(index, 1);
		},
		// 失去焦点
		handleInput(row,type){
			this.confirmEdit(row,type)
		},
		// 双击编辑
		handleCellClick(row, column, event, cell) {
			let index = row.index
			if (column.label === '进货价'  ) {
				this.orderGoodList[''+index+''].editPrice = !this.orderGoodList[''+index+''].editPrice;
			}
			if (column.label === '进货数量'  ) {
				this.orderGoodList[''+index+''].editQuantity = !this.orderGoodList[''+index+''].editQuantity;
			}
		},
		// 取消编辑
		cancelEdit(row,type) {
			row.goodInPrice = row.originalGoodInPrice;
			if(type === 'price'){
				row.editPrice = false;
			}else{
				row.editQuantity = false;
			}
		},
		// 表格编辑
		confirmEdit(row,type) {
			if(type === 'price'){
				row.editPrice = false;
			}else{
				row.editQuantity = false;
			}		
			row.originalGoodInPrice = row.goodInPrice;
			
			// 计算采购费用
			row.totalPrice  = row.quantity * row.goodInPrice
		},
		submit() {
			let arr =this.orderGoodList;
			let paramArr = arr.splice(0,arr.length-1);
			// for(let index in paramArr){
			// 	paramArr[''+index+''].quantity = Number(paramArr[''+index+''].quantity)
			// }
			if(paramArr.length == 0){
				this.$message({
					message:"请选择要进货的商品",
					type:"warning"
				})
				return;
			}
			this.$store.dispatch('purorder/batch',paramArr).then(res => {
				console.log(res)
				if(res.code === 200){
					this.$message({
						message:"进货单提交成功",
						type:"success"
					})
				}else{
					this.$message({
						message:res.message,
						type:"error"
					})
					return;
				}
			});
		},
		// 选择商品dialog
		showDialog(index) {
			this.getAll();
			this.dialogVisible = true;
		},
		storeColseDialog(index) {
			this.dialogVisible = false;
			let tmpGoodListArr = this.tmpGoodList;
			let orderGoodListArr = this.orderGoodList;
			this.orderGoodList.pop(); //删除空行
			for (let index in tmpGoodListArr) {
				let tmpGoodItem = tmpGoodListArr[index];
				let obj = JSON.parse(JSON.stringify(orderGood)) ;
				obj.goodName = tmpGoodItem.goodName;
				obj.goodNo = tmpGoodItem.goodNo;
				obj.goodId = tmpGoodItem.id;
				obj.goodPrice = tmpGoodItem.goodPrice;
				obj.goodStock = tmpGoodItem.goodStock;
				obj.saleNum = tmpGoodItem.saleNum;
				this.orderGoodList.push(obj);
			}
			//this.orderGoodList = orderGoodListArr;
			this.tmpGoodList = [];
			this.orderGoodList.push(orderGood); // 添加一个空的行
		},
		handleSelectChange(val) {
			this.tmpGoodList = val;
		},
		// dialog 关闭事件
		handleClose(done) {
			this.$confirm('确认关闭？')
				.then(_ => {
					done();
				})
				.catch(_ => {});
		},
		getAll() {
			this.listLoading = true;
			var param = {
				pageNum: this.pageNum,
				pageSize: this.pageSize
			};
			this.$store.dispatch('good/getAll', param).then(res => {
				this.goodList = res.data.list;
				this.total = res.data.total;
				this.listLoading = false;
			});
		}
	}
};
</script>
<style>
.el-table {
	margin-top: 20px;
}
.mainImage {
	width: 50px;
	height: 50px;
}
.button-container {
	margin-top: 20px;
	width: 100%;
}
</style>
